package data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import utils.Utils;

public class DataUtils {

	/**
	 * combines data with the same independent data values, into a single data object
	 * 
	 * The data from column <code>aCol</code> becomes the independent column
	 * and the data from column <code>bCol</code> becomes the dependent column
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static Data intersect(Data a, int aCol,  Data b, int bCol) {
		double[] keeperTimes = keepEquals(a.getIndependent(), b.getIndependent());
		
		int[] aIndices = getIndicesFromKeepers(a.getIndependent(), keeperTimes);
		int[] bIndices = getIndicesFromKeepers(b.getIndependent(), keeperTimes);
		
		double[] indy = getValuesFromIndices(a.getDataColumn(aCol), aIndices);
		double[] dep = getValuesFromIndices(b.getDataColumn(bCol), bIndices);
		
		String indyName = a.getColumnNames()[aCol];
		String depName = b.getColumnNames()[bCol];
		String[] colNames = {indyName, depName};
		
		String dataName = a.getDataName() + " merged " + b.getDataName();
		
		return new Data(dataName, colNames, indy, new double[][] {dep});
	}

	public static double[] keepEquals(double[] a, double[] b) {
		List<Double> aList = new ArrayList<Double>();
		for(double d : a){
			aList.add(d);
		}
		
		List<Double> bList = new ArrayList<Double>();
		for(double d : b){
			bList.add(d);
		}
		
		
		aList.retainAll(bList);
		double[] rtn = Utils.getDoubleValues(aList);
		return rtn;
		
	}

	public static int[] getIndicesFromKeepers(double[] input, double[] keepers) {
		int[] indices = new int[keepers.length];
		for(int i=0;i<keepers.length;i++){
			int index = Arrays.binarySearch(input, keepers[i]);
			indices[i] = index;
		}
		return indices;
	}

	public static double[] getValuesFromIndices(double[] values, int[] indices) {
		double[] rtn = new double[indices.length];
		for(int i=0;i<rtn.length;i++){
			rtn[i] = values[indices[i]];
		}
		return rtn;
	}

	
}
